﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using weizhiyuntest.Resources;
using Microsoft.WindowsAzure.MobileServices;

using Newtonsoft.Json;
using Com.AMap.Api.Maps;
using Com.AMap.Api.Maps.Model;
using System.Windows.Media;
using Com.AMap.Api.Services.Results;
using Com.AMap.Api.Services;

namespace weizhiyuntest
{
   
    public partial class MainPage : PhoneApplicationPage
    {
        AMapGeolocator mylocation;
      public static  AMap amap;
      AMapMarker marker;
      //圆
      AMapCircle circle;
        private IMobileServiceTable<weizhi> ta = App.MobileService.GetTable<weizhi>();
      //  List<xy> xyo = new List<xy>();
        List<LatLng> xyo = new List<LatLng>();
        LatLng dhstart;
        LatLng dhend;
        // 构造函数
        public MainPage()
        {
            InitializeComponent();
          
           
            // 用于本地化 ApplicationBar 的示例代码
            //BuildLocalizedApplicationBar();
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            weizhi w = new weizhi() { lx = "1231", ly = "2424" };
      // await    ta.InsertAsync(w);
            DateTime dt1 = dp1.Value.Value;
       //    var biao = await App.MobileService.GetTable<weizhi>().Where(h => h.Id != null).ToCollectionAsync();
            var biao1 = await App.MobileService.GetTable<weizhi>().ToListAsync();
            var biao = biao1.Where(h => h.riqi.DayOfYear == dt1.DayOfYear && h.riqi.Year == dt1.Year).ToList();

         //   var biao = await App.MobileService.GetTable<weizhi>().Where(h => h.riqi.DayOfYear == dt1.DayOfYear && h.riqi.Year == dt1.Year).ToCollectionAsync();
            int a = 0;
            foreach (var b in biao.ToList())
            {
                if (!xyo.Contains(new LatLng(Convert.ToDouble(b.lx),Convert.ToDouble(b.ly)))) 
                {

                    xyo.Add(new LatLng(Convert.ToDouble(b.lx),Convert.ToDouble(b.ly)));
                }
            }

            amap.AddPolyline(new AMapPolylineOptions()
            {
                Points = xyo,
                Color = Color.FromArgb(255, 0, 0, 255),
                Width = 4,
            });
           
 
  

     //  lsta.ItemsSource = xyo;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (amap == null)
            {
                this.ContentPanel.Children.Add(amap = new AMap());
                amap.UpdateLayout();
                amap.Tap += amap_Tap;
            }
            else
            {
                this.ContentPanel.Children.Add(amap);
                amap.Tap += amap_Tap;
            }
        }

        private void PhoneApplicationPage_Unloaded(object sender, RoutedEventArgs e)
        {
            amap = null;
            this.ContentPanel.Children.Clear();
            
        }
        void amap_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //throw new NotImplementedException();
            Point p = e.GetPosition(amap);//获得在map容器的像素坐标

            this.dhend = amap.GetProjection().FromScreenLocation(p);
            marker = amap.AddMarker(new AMapMarkerOptions()
            {
                Position = this.dhend,
                Title = "Title",
                Snippet = "Snippet",
                IconUri = new Uri("Images/AZURE.png", UriKind.Relative),
            });
        }
       

        private void ListPicker_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
       // string yonghu=    (sender as ListPicker).SelectedItem.ToString();
      //  int a = 3;
            
            
           
			// 在此处添加事件处理程序实现。
        }

        private void ListPickerItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //this.ContentPanel.Visibility = Visibility.Collapsed;
           
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            mylocation = new AMapGeolocator();
            mylocation.Start();
            //触发位置改变事件
            mylocation.PositionChanged += mylocation_PositionChanged;
        }

        // 用于生成本地化 ApplicationBar 的示例代码
        //private void BuildLocalizedApplicationBar()
        //{
        //    // 将页面的 ApplicationBar 设置为 ApplicationBar 的新实例。
        //    ApplicationBar = new ApplicationBar();

        //    // 创建新按钮并将文本值设置为 AppResources 中的本地化字符串。
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // 使用 AppResources 中的本地化字符串创建新菜单项。
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}

        void mylocation_PositionChanged(AMapGeolocator sender, AMapPositionChangedEventArgs args)
        {
            this.dhstart = args.LngLat;
            this.Dispatcher.BeginInvoke(() =>
            {
                if (marker == null)
                {
                    //添加圆
                    circle = amap.AddCircle(new AMapCircleOptions()
                    {
                        Center = args.LngLat,//圆点位置
                        Radius = (float)args.Accuracy,//半径
                        FillColor = Color.FromArgb(80, 100, 150, 255),
                        StrokeWidth = 2,//边框粗细
                        StrokeColor = Color.FromArgb(80, 0, 0, 255),//边框颜色

                    });

                    //添加点标注，用于标注地图上的点
                    marker = amap.AddMarker(
                   new AMapMarkerOptions()
                   {
                       Position = args.LngLat,//图标的位置
                       Title = "我的位置",
                       IconUri = new Uri("Images/marker_gps_no_sharing.png", UriKind.Relative),//图标的URL
                       Anchor = new Point(0.5, 0.5),//图标中心点

                   });
                }
                else
                {
                    //点标注和圆的位置在当前经纬度
                    marker.Position = args.LngLat;
                    circle.Center = args.LngLat;
                    circle.Radius = (float)args.Accuracy;//圆半径
                }

                //设置当前地图的经纬度和缩放级别
                amap.MoveCamera(CameraUpdateFactory.NewLatLngZoom(args.LngLat, 15));
              
            });
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            GetNavigationDriving(this.dhstart, this.dhend);
        }
        private async void GetNavigationDriving(LatLng start, LatLng end)
        {
            //请求查询，origin、destination为起点和终点，是必选项  
            AMapRouteResults rts = await AMapNavigationSearch.DrivingNavigation(start.longitude, start.latitude, end.longitude, end.latitude, Extensions.All);
            if (rts.Erro == null)
            {
                if (rts.Count == 0)
                {
                    MessageBox.Show("无查询结果");
                    return;
                }
                AMapRoute route = rts.Route;
                List<AMapPath> paths = route.Paths.ToList();
                List<LatLng> lnglats = new List<LatLng>();
                foreach (AMapPath item in paths)
                {
                    
                    //画路线  
                    List<AMapStep> steps = item.Steps.ToList();
                    foreach (AMapStep st in steps)
                    {
                        
                        lnglats = latLagsFromString(st.Polyline);
                        amap.AddPolyline(new AMapPolylineOptions()
                        {
                            Points = latLagsFromString(st.Polyline),
                            Color = Color.FromArgb(255, 0, 0, 255),
                            Width = 4,
                        });
                    }
                }
            }
            else
            {
                MessageBox.Show(rts.Erro.Message);
            }
        }
        private List<LatLng> latLagsFromString(string polyline)
        {
            List<LatLng> latlng = new List<LatLng>();

            string[] arrystring = polyline.Split(new char[] { ';' });
            foreach (String str in arrystring)
            {
                String[] lnglatds = str.Split(new char[] { ',' });
                latlng.Add(new LatLng(Double.Parse(lnglatds[1]), Double.Parse(lnglatds[0])));
            }
            return latlng;

        }
    }
  
}